package com.atguigu.tingshu.user.strategy.impl;

import com.atguigu.tingshu.album.client.TrackInfoFeignClient;
import com.atguigu.tingshu.common.constant.SystemConstant;
import com.atguigu.tingshu.common.result.Result;
import com.atguigu.tingshu.model.album.TrackInfo;
import com.atguigu.tingshu.model.user.UserPaidTrack;
import com.atguigu.tingshu.user.mapper.UserPaidTrackMapper;
import com.atguigu.tingshu.user.strategy.ItemTypeStrategy;
import com.atguigu.tingshu.vo.user.UserPaidRecordVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;

import java.util.List;

/**
 * @author atguigu-mqx
 * @ClassName TrackStrategy
 * @description: TODO
 * @date 2024年08月13日
 * @version: 1.0
 */
@Component("1002")
public class TrackStrategy implements ItemTypeStrategy {

    @Autowired
    private UserPaidTrackMapper userPaidTrackMapper;

    @Autowired
    private TrackInfoFeignClient trackInfoFeignClient;

    @Override
    public void savePaidRecord(UserPaidRecordVo userPaidRecordVo) {
        //  声音 user_paid_track
        Long count = userPaidTrackMapper.selectCount(new LambdaQueryWrapper<UserPaidTrack>().eq(UserPaidTrack::getUserId, userPaidRecordVo.getUserId()).eq(UserPaidTrack::getOrderNo, userPaidRecordVo.getOrderNo()));
        if (count > 0) {
            return;
        }
        //  创建对象并保存数据
        List<Long> itemIdList = userPaidRecordVo.getItemIdList();
        //  需要根据声音Id获取到声音对象;
        Result<TrackInfo> trackInfoResult = trackInfoFeignClient.getTrackInfo(itemIdList.get(0));
        Assert.notNull(trackInfoResult, "trackInfoResult不能为空");
        TrackInfo trackInfo = trackInfoResult.getData();
        Assert.notNull(trackInfo, "trackInfo不能为空");
        if (!CollectionUtils.isEmpty(itemIdList)) {
            for (Long trackId : itemIdList) {
                UserPaidTrack userPaidTrack = new UserPaidTrack();
                //  赋值：
                userPaidTrack.setTrackId(trackId);
                userPaidTrack.setOrderNo(userPaidRecordVo.getOrderNo());
                userPaidTrack.setUserId(userPaidRecordVo.getUserId());
                //  获取专辑对象：才能赋值专辑Id;
                userPaidTrack.setAlbumId(trackInfo.getAlbumId());
                userPaidTrackMapper.insert(userPaidTrack);
            }
        }
    }
}
